<?php

    @header("Content-Type:text/html;charset=utf-8");    // 配置php文件返回的 文本类型 编码(适应低版本)         => php 向 前端 返回的数据类型、

    @include_once("../../php/conn.php");      //引入公共的php 

    $key = $_GET["key"];                // 搜索关键词
    $orderCol = $_GET["orderCol"];      // 排序列名
    $orderType = $_GET["orderType"];    // 排序方式
    $showNum = $_GET["showNum"];                // 显示条数
    $pageIndex = $_GET["pageIndex"];  
    
    
    if(!($orderCol && $orderType && $showNum && $pageIndex)) {
        $obj = array();
        $obj["status"] = false;
        $obj["msg"] = "请输入完整参数";
        exit(json_encode($obj) );
    }

    
    // 查询数据的总数量(按照搜索关键词查找)
        $searchAll = "select count(*) as count from `grade` where name like '%$key%'";
        $resultAll = mysqli_query($conn,$searchAll); 
        $item = mysqli_fetch_assoc($resultAll);
        $count = $item["count"];

    // $pageIndex  可能超过最大值 也可能小于1  =>  需要限制范围
    // 页码的最大值 maxPage = count / showNum => 向上取整
        $maxPage = ceil($count / $showNum);
        if($pageIndex >= $maxPage) {
            $pageIndex = $maxPage;
        }
        if($pageIndex <= 1) {
            $pageIndex = 1;
        }


    $skipNum = ($pageIndex - 1) * $showNum;


    $search = "select id, name, class, chinese, math, english, chinese+math+english as total from `grade` where name like '%$key%' order by $orderCol $orderType limit $skipNum,$showNum";
    $result = mysqli_query($conn,$search); 

    $arr = array();
    while($item = mysqli_fetch_assoc($result)) { 
    // 数据处理     
        $item["chinese"] = $item["chinese"]*1;
        $item["math"] = $item["math"]*1;
        $item["english"] = $item["english"]*1;
        $item["total"] = $item["total"]*1;

        array_push($arr,$item);
    };
    // echo json_encode($arr);

    // 传送多个数据

    $obj = array();
    $obj["list"] = $arr;
    $obj["count"] = $count;
    $obj["maxPage"] = $maxPage;

    echo json_encode($obj);

?>